import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
import {RelatedCondition} from '../model/related-condition';
import {RelatedPolicyListService} from './related-policy-list.service';

@Component({
  selector: 'app-related-policy-list',
  templateUrl: './related-policy-list.component.html',
  styleUrls: ['./related-policy-list.component.less']
})
export class RelatedPolicyListComponent implements OnInit {
  titleName;
  getRelatedCondition = new RelatedCondition();
  relatedList = [];
  regionList = [];
  selectedTab = 0;
  isSpinning;

  constructor(private route: ActivatedRoute,
              private relatedService: RelatedPolicyListService) {
  }

  ngOnInit(): void {
    this.route.queryParams.pipe().subscribe((params: Params) => {
      if (params.wordFrameId) {
        this.getRelatedCondition.wordFreamId = Number(params.wordFrameId);
      }
      if (params.policyId) {
        this.getRelatedCondition.policyId = Number(params.policyId);

      }
      if (params.wordFrameName) {
        this.titleName = params.wordFrameName;
      }
    });
    this.getRegions();
  }

  getRegions() {
    this.isSpinning = true;
    this.relatedService.getRegionList(this.getRelatedCondition).subscribe(res => {
      let arr = [];
      if (res.result && res.result.length > 0) {
        // 1.预处理数据, 排序
        let sorted = ['上海市', '北京市', '广东省深圳市', '广东省广州市', '天津市', '浙江省杭州市', '江苏省南京', '湖北省武汉市'];
        let arr2 = [];
        sorted.forEach(item2 => {
          if (res.result.indexOf(item2) > -1) {
            arr2.push(item2);
            res.result.splice(res.result.indexOf(item2), 1);
          }
        });
        res.result.forEach(item2 => {
          arr2.push(item2);
        });
        // 2.预处理数据, ['广东省广州市', '北京市'] 改为 [{name:'广东省广州市', show:'广州市'}, {name:'北京市', show:'北京市'}]
        arr = [];
        arr2.forEach(item => {
          arr.push({name: item, show: item.replace(/^.*省/gi, '')});
        });
      }
      //console.log(arr);
      this.regionList = arr;    // res.result;
      if (this.regionList) {
        this.getRelatedCondition.region = this.regionList[0]?.name;
      }
      this.getRelatedList();
    });
  }

  getRelatedList() {
    this.isSpinning = true;
    this.relatedService.getRelatedList(this.getRelatedCondition).subscribe(res => {
      this.relatedList = [];
      this.relatedList = res.result.list;
      this.isSpinning = false;
    });
  }

  transformHtml(content: string) {
    return content.replace(/<[^>]+>/g, '').replace(/&nbsp;/ig, '');
  }

  tabActivated() {
    console.log('[tabActivated]', this.selectedTab);
    this.getRelatedCondition.region = this.regionList[this.selectedTab].name;
    this.getRelatedList();
  }
}
